import random
import sys
import time

from PyQt5.QtCore import Qt, QCoreApplication, QSize, QRectF, QTimer
from PyQt5.QtGui import QImage, QPixmap, QPainter, QWheelEvent, QBrush, QPen
from PyQt5.QtWidgets import (QWidget, QGraphicsItem, QFileDialog, QApplication, QMainWindow, QGraphicsScene,
                             QGraphicsView,
                             QGraphicsTextItem, QGraphicsEllipseItem, QGraphicsRectItem,
                             QGraphicsPixmapItem, QGraphicsPolygonItem, QGraphicsPathItem)
# from PIL import Image, ImageDraw

# import matplotlib.pyplot as plt


# """ 图片查看器 """
from windowUI.view2DUI import Ui_view2DWidget


class View2DWindow(Ui_view2DWidget, QWidget):
    windowH, windowW = 300, 300
    minRectX, minRectY = 1, 1

    # __timer = QTimer()
    def __init__(self, parent=None):
        super().__init__(parent=parent)
        self.setupUi(self)
        # 引入公共程序
        from utils.common import commonProgram
        # 引入配置文件
        self.myConfig = commonProgram.EnableConfigHandler()
        print('View2DWindow get config Version', self.myConfig.version)
        self.connect_init()
        # 创建场景
        # 参数：场景区域
        # 场景坐标原点默认在场景中心---场景中心位于界面中心
        # 设置场景起始及大小，默认场景是中心为起始，不方便后面的代码
        self.graphicsScene = QGraphicsScene(QRectF(0, 0, self.windowW, self.windowH))
        self.graphicsView.setScene(self.graphicsScene)
        # 将场景添加至视图
        self.graphicsView.setAlignment(Qt.AlignLeft | Qt.AlignTop)

    def connect_init(self):
        self.btnRefresh.clicked.connect(self.RefreshDataFun)
        self.btnSaveImg.clicked.connect(self.SaveImgFun)
        self.RefreshDataFun()

    def RefreshDataFun(self):
        self.windowW = int(self.screenLength.currentText().strip())
        self.windowH = int(self.screenWidth.currentText().strip())
        self.minRectX, self.minRectY = self.minRectL.value(), self.minRectW.value()
        self.graphicsView.resize(self.windowW, self.windowH)
        # 隐藏滚动条
        self.graphicsView.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.graphicsView.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        # 以鼠标所在位置为锚点进行缩放
        self.graphicsView.setTransformationAnchor(self.graphicsView.AnchorUnderMouse)
        # 平滑缩放
        # self.pixmapItem.setTransformationMode(Qt.SmoothTransformation)
        self.graphicsView.setRenderHints(QPainter.Antialiasing |
                                         QPainter.SmoothPixmapTransform)
        # 初始化小部件
        # self.imgObj = Image.new('RGB', (self.imageX, self.imageY), (255, 255, 255))
        # self.__timer.timeout.connect(self.DrawRectFun)
        # self.__timer.start(1000)

    def SaveImgFun(self):
        # filepath, type = QFileDialog.getSaveFileName(self, "保存图像", '', filter='image(*.png,*.jpg,*.bmp)')
        # print('保存图像：', filepath, type)
        # self.imgObj.save(filepath)
        # 接收来自主界面的数据
        # rect = QGraphicsView.viewport(self.dlg.gvPointRecords).rect()
        rect = self.graphicsScene.sceneRect()
        ## QImage 保存为透明背景
        # pixmap = QImage(self.graphicsView.rect().width(), self.graphicsView.rect().height(),QImage.Format_ARGB32_Premultiplied)
        # 抓取View的图像
        pixmap = QPixmap(self.graphicsView.grab())
        painter = QPainter(pixmap)
        rectf = QRectF(0, 0, pixmap.rect().height(), pixmap.rect().width())
        # painter.begin(pixmap)
        self.graphicsScene.render(painter, rectf, rect)
        imagePath, type = QFileDialog.getSaveFileName(self, "保存图像", './', "影像 (*.png *.jpg)")
        if imagePath:
            print(imagePath, type)
            img = pixmap.save(imagePath)
        else:
            print(imagePath, type)
            # self.imgObj = Image.new('RGB', (self.windowW, self.windowW), (255, 255, 255))
            # draw_obj = ImageDraw.Draw(self.pixmap)
            # draw_obj.rectangle(QRectF(self.graphicsView.rect()), fill=(0, 255, 255), outline="#000000", width=1)
            # self.imgObj.save(imagePath)
        painter.end()

    def DrawRectFun(self, rectX=0, rectY=0):
        # 画长方形
        # xy – 定义边界框，[(x0, y0), (x1, y1)] or [x0, y0, x1, y1],
        # outline – 轮廓线条颜色
        # fill – 填充颜色
        # width – 线条宽度，单位 pixels
        drawX0 = rectX * self.minRectX
        drawY0 = rectY * self.minRectY
        # drawX1 = drawX0 + self.minRectX
        # drawY1 = drawY0 + self.minRectY
        # 添加一个顺时针旋转30°的矩形
        # x,y,w,h
        rect = QGraphicsRectItem(drawX0, drawY0, self.minRectX, self.minRectY)
        rect.setPen(QPen(Qt.blue))
        rect.setBrush(QBrush(Qt.blue))
        # rect.setRotation(30)  # 旋转30度
        # rect.setPos(drawX0, drawY0)
        # 设置场景
        self.graphicsScene.addItem(rect)

    # {"data":XX,"type":0,}
    # type : 0-指令(直接发送)
    def RecvMainData(self, dictData):
        typeValue = dictData.get("type", 0)
        dataStr = dictData.get('data', None)
        # 接受Form1传过来的msg，保存到自己的变量里面。
        print('view2D 收到 来自主界面信息：{}，type: {}'.format(dataStr, typeValue))
        if not dataStr:
            return
        if typeValue == 0:
            self.DrawRectFun(rectX=int(dataStr.get("x", 0)), rectY=int(dataStr.get("y", 0)))
            # print('换颜色')
    # def MakeColorImage(self, rectX=0, rectY=0, imagePath='./tempImg.png'):
    #     draw_obj = ImageDraw.Draw(self.imgObj)
    #     # 画长方形
    #     # xy – 定义边界框，[(x0, y0), (x1, y1)] or [x0, y0, x1, y1],
    #     # outline – 轮廓线条颜色
    #     # fill – 填充颜色
    #     # width – 线条宽度，单位 pixels
    #     drawX0 = rectX * self.minRectX
    #     drawY0 = rectY * self.minRectY
    #     drawX1 = drawX0 + self.minRectX
    #     drawY1 = drawY0 + self.minRectY
    #     draw_obj.rectangle((drawX0, drawY0, drawX1, drawY1), fill=(0, 255, 255), outline="#000000", width=1)
    #     # .point((1, 2), fill=(0, 255, 255))
    #     self.imgObj.save(imagePath)
    #     return imagePath


# 程序入口
if __name__ == "__main__":
    QCoreApplication.setAttribute(Qt.AA_EnableHighDpiScaling)
    app = QApplication(sys.argv)
    view2DWindow = View2DWindow()
    view2DWindow.show()
    for i in range(720):
        for j in range(420):
            if i == j:
                view2DWindow.DrawRectFun(rectX=i, rectY=j)
                # view2DWindow.DrawRectFun(rectX=random.randint(0, i), rectY=random.randint(0, i))
        # time.sleep(0.001)
    sys.exit(app.exec_())
